package com.imonsoft.sqm.web.business.ipic_system;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.imonsoft.common.editor.DateEditor;
import com.imonsoft.sqm.pojo.basedata.Part;
import com.imonsoft.sqm.pojo.basedata.Supplier;
import com.imonsoft.sqm.service.basedata.PartService;
import com.imonsoft.sqm.service.basedata.SupplierService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.imonsoft.common.constant.CCommon;
import com.imonsoft.common.constant.ConstantDict;
import com.imonsoft.common.constant.ConstantSqm;
import com.imonsoft.common.exception.SystemException;
import com.imonsoft.common.httpModel.DataGrid;
import com.imonsoft.common.httpModel.Pager;
import com.imonsoft.common.httpModel.ReturnMessage;
import com.imonsoft.common.util.AjaxUtil;
import com.imonsoft.common.util.ContextUtil;
import com.imonsoft.common.util.DateUtil;
import com.imonsoft.common.util.JsonUtil;
import com.imonsoft.common.util.upload.ImageUploadUtil;
import com.imonsoft.sqm.pojo.basedata.Dictionary;
import com.imonsoft.sqm.pojo.business.ipic_system.Claim;
import com.imonsoft.sqm.service.basedata.DictionaryService;
import com.imonsoft.sqm.service.business.ipic_system.ClaimFieldService;
import com.imonsoft.sqm.validator.business.ipic_system.ClaimValidator;
import com.imonsoft.sqm.vo.business.ipic_system.ClaimVo;

@Controller
@RequestMapping("/business/ipic_system/claim_field")
public class ClaimFieldController {
    protected final Log logger = LogFactory.getLog(getClass());
    @Autowired
    private ClaimFieldService claimFieldService;
    @Autowired
    private ClaimValidator claimValidator;
    @Autowired
    private DictionaryService dictionaryService;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private PartService partService;

    @RequestMapping("/listUI.do")
    public void listUI(ModelMap model) {
        List<Dictionary> dictWorkshopList = dictionaryService.findDictionaryByType(ConstantDict.WORKSHOP);
        model.put("dictWorkshopList", dictWorkshopList);
        List<Dictionary> dictFindPlaceList = dictionaryService.findDictionaryByType(ConstantDict.FIND_PLACE);
        model.put("dictFindPlaceList", dictFindPlaceList);
        List<Dictionary> dictManageBodyList = dictionaryService.findDictionaryByType(ConstantDict.MANAGE_BODY);
        model.put("dictManageBodyList", dictManageBodyList);
        List<Dictionary> dictClaimStatusList = dictionaryService.findDictionaryByType(ConstantDict.CLAIM_STATUS);
        model.put("dictClaimStatusList", dictClaimStatusList);
        List<Dictionary> dictClaimTypeList = dictionaryService.findDictionaryByType(ConstantDict.CLAIM_TYPE);
        model.put("dictClaimTypeList", dictClaimTypeList);
    }

    @RequestMapping(value = "/ajaxList.do", method = RequestMethod.POST)
    public void ajaxList(HttpServletResponse response, Pager pager, Claim claim) {
        DataGrid<ClaimVo> dataGrid = new DataGrid<ClaimVo>();
        try {
            List<ClaimVo> claimVoList = new ArrayList<ClaimVo>();
            DataGrid<Claim> claimDataGrid = claimFieldService.getDataGrid(claim, pager);
            List<Claim> claimList = claimDataGrid.getRows();
            for (Claim entity : claimList) {
                ClaimVo entityVo = new ClaimVo();
                BeanUtils.copyProperties(entity, entityVo);
                entityVo.setStartDateStr(DateUtil.date2string(null == entity.getStartDate() ? null : entity.getStartDate()));
                entityVo.setCloseDatePlanStr(DateUtil.date2string(null == entity.getCloseDatePlan() ? null : entity.getCloseDatePlan()));
                entityVo.setCloseDateActualStr(DateUtil.date2string(null == entity.getCloseDateActual() ? null : entity.getCloseDateActual()));
                entityVo.setManufactureDateStr(DateUtil.date2string(null == entity.getManufactureDate() ? null : entity.getManufactureDate()));

                entityVo.setCs4Str(DateUtil.date2string(null == entity.getCs4() ? null : entity.getCs4()));
                entityVo.setCs5Str(DateUtil.date2string(null == entity.getCs5() ? null : entity.getCs5()));
                entityVo.setCs6Str(DateUtil.date2string(null == entity.getCs6() ? null : entity.getCs6()));
                entityVo.setCs7Str(DateUtil.date2string(null == entity.getCs7() ? null : entity.getCs7()));
                entityVo.setCs8Str(DateUtil.date2string(null == entity.getCs8() ? null : entity.getCs8()));
                claimVoList.add(entityVo);
            }
            dataGrid.setRows(claimVoList);
            dataGrid.setTotal(claimDataGrid.getTotal());
        } catch (SystemException se) {
            logger.info(se.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        AjaxUtil.renderJSON(response, JsonUtil.bean2json(dataGrid));
    }

    @RequestMapping("/addUI.do")
    public void addUI(ModelMap model) {
        List<Dictionary> dictWorkshopList = dictionaryService.findDictionaryByType(ConstantDict.WORKSHOP);
        model.put("dictWorkshopList", dictWorkshopList);
        List<Dictionary> dictProductTypeList = dictionaryService.findDictionaryByType(ConstantDict.PART_PRODUCT_TYPE);
        model.put("dictProductTypeList", dictProductTypeList);
        List<Dictionary> dictFindPlaceList = dictionaryService.findDictionaryByType(ConstantDict.FIND_PLACE);
        model.put("dictFindPlaceList", dictFindPlaceList);
        List<Dictionary> dictReportCodeNotQualifiedList = dictionaryService.findDictionaryByType(ConstantDict.REPORT_CODE_NOT_QUALIFIED);
        model.put("dictReportCodeNotQualifiedList", dictReportCodeNotQualifiedList);
        List<Dictionary> dictManageBodyList = dictionaryService.findDictionaryByType(ConstantDict.MANAGE_BODY);
        model.put("dictManageBodyList", dictManageBodyList);
        List<Dictionary> dictClaimStatusList = dictionaryService.findDictionaryByType(ConstantDict.CLAIM_STATUS);
        model.put("dictClaimStatusList", dictClaimStatusList);
        ClaimVo claimVo = new ClaimVo();
        claimVo.setYear((DateUtil.getNowYear() + "").substring(2, 4));
        claimVo.setStartDateStr(DateUtil.getNowDate());
        model.put("claimVo", claimVo);
    }

    @RequestMapping(value = "/ajaxAdd.do", method = RequestMethod.POST)
    public void ajaxAdd(HttpServletResponse response, Claim claim, BindingResult result) {
        ReturnMessage message = new ReturnMessage();
        try {
            claimValidator.methodAddValidate(claim, result);
            if (result.hasErrors()) {
                message.setObj(claimValidator.getErrors(result));
            } else {
                claimFieldService.insert(claim);
                message.setSuccess(true);
                message.setMsg(ConstantSqm.OPERATE_SUCCESS);
            }
        } catch (SystemException se) {
            logger.info(se.getMessage());
            message.setMsg(se.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage());
            message.setMsg(CCommon.EXCEPTION_MSG);
        }
        AjaxUtil.renderJSON(response, JsonUtil.bean2json(message));
    }

    @RequestMapping(value = "/modifyUI.do")
    public void modifyUI(ModelMap model, Long id) {
        if (null != id) {
            Claim claim = claimFieldService.get(id);
            ClaimVo claimVo = new ClaimVo();
            BeanUtils.copyProperties(claim, claimVo);
            Supplier supplier = supplierService.get(claim.getSupplierId());
            claimVo.setSupplierMail(supplier.getMail() == null ? "" : supplier.getMail());
            claimVo.setSupplierPhone(supplier.getPhone() == null ? "" : supplier.getPhone());
            claimVo.setSupplierLinkman(supplier.getLinkman() == null ? "" : supplier.getLinkman());
            Part part=partService.get(claim.getPartId());
            claimVo.setPartDrawingCode(part.getDrawingCode());

            claimVo.setStartDateStr(DateUtil.date2string(null == claim.getStartDate() ? null : claim.getStartDate()));
            claimVo.setManufactureDateStr(DateUtil.date2string(null == claim.getManufactureDate() ? null : claim.getManufactureDate()));

            claimVo.setCs1Str(DateUtil.date2string(null == claim.getCs1() ? null : claim.getCs1()));
            claimVo.setCs2Str(DateUtil.date2string(null == claim.getCs2() ? null : claim.getCs2()));
            claimVo.setCs3Str(DateUtil.date2string(null == claim.getCs3() ? null : claim.getCs3()));
            claimVo.setCs4Str(DateUtil.date2string(null == claim.getCs4() ? null : claim.getCs4()));
            claimVo.setCs5Str(DateUtil.date2string(null == claim.getCs5() ? null : claim.getCs5()));
            claimVo.setCs6Str(DateUtil.date2string(null == claim.getCs6() ? null : claim.getCs6()));
            claimVo.setCs7Str(DateUtil.date2string(null == claim.getCs7() ? null : claim.getCs7()));
            claimVo.setCs8Str(DateUtil.date2string(null == claim.getCs8() ? null : claim.getCs8()));
            model.put("entity", claimVo);
        } else {
            throw new SystemException(ConstantSqm.DATA_ERROR);
        }
        List<Dictionary> dictWorkshopList = dictionaryService.findDictionaryByType(ConstantDict.WORKSHOP);
        model.put("dictWorkshopList", dictWorkshopList);
        List<Dictionary> dictFindPlaceList = dictionaryService.findDictionaryByType(ConstantDict.FIND_PLACE);
        model.put("dictFindPlaceList", dictFindPlaceList);
        List<Dictionary> dictManageBodyList = dictionaryService.findDictionaryByType(ConstantDict.MANAGE_BODY);
        model.put("dictManageBodyList", dictManageBodyList);
        List<Dictionary> dictClaimStatusList = dictionaryService.findDictionaryByType(ConstantDict.CLAIM_STATUS);
        model.put("dictClaimStatusList", dictClaimStatusList);
    }

    @RequestMapping(value = "/ajaxModify.do", method = RequestMethod.POST)
    public void ajaxModify(HttpServletResponse response, Claim claim, BindingResult result) {
        ReturnMessage message = new ReturnMessage();
        try {
            claimValidator.validate(claim, result);
            if (result.hasErrors()) {
                message.setObj(claimValidator.getErrors(result));
            } else {
                claimFieldService.update(claim);
                message.setSuccess(true);
                message.setMsg(ConstantSqm.OPERATE_SUCCESS);
            }

        } catch (SystemException se) {
            logger.info(se.getMessage());
            message.setMsg(se.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage());
            message.setMsg(CCommon.EXCEPTION_MSG);
        }
        AjaxUtil.renderJSON(response, JsonUtil.bean2json(message));
    }

    @RequestMapping(value = "/ajaxDelete.do", method = RequestMethod.POST)
    public void ajaxDelete(HttpServletResponse response, @RequestParam("ids") List<Long> idList) {
        ReturnMessage message = new ReturnMessage();
        try {
            claimFieldService.deleteClaim(idList);
            message.setSuccess(true);
            message.setMsg(ConstantSqm.OPERATE_SUCCESS);
        } catch (SystemException se) {
            logger.info(se.getMessage());
            message.setMsg(se.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage());
            message.setMsg(CCommon.EXCEPTION_MSG);
        }
        AjaxUtil.renderJSON(response, JsonUtil.bean2json(message));
    }

    /**
     * 上传图片
     */
    @RequestMapping(value = "/upImage", method = RequestMethod.POST)
    public void upImage(HttpServletRequest request, HttpServletResponse response) {
        String result = "";
        ReturnMessage message = new ReturnMessage();
        String str = "<script type=\"text/javascript\"> window.parent.OnUploadCompleted('#reslut#');</script>";
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            // 获得文件
            MultipartFile mFile = multipartRequest.getFile("fileUp");
            // 设置相应的规格参数
            int guige[][] = {{100, 100}, {206, 400}, {130, 130}};
            String url = ImageUploadUtil.imageUpload(mFile, guige);
            result = ContextUtil.getFlashMessage();

            message.setSuccess(true);
            message.setObj(url);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            message.setMsg("操作失败！");
        }
        result = JsonUtil.bean2json(message);
        AjaxUtil.renderHTML(response, str.replaceFirst("#reslut#", result));
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new DateEditor(dateFormat));
    }
}
